import axios from 'axios'

const state = {
  items: [],
  loading: false,
  error: null
}

const mutations = {
  SET_PLANTS(state, plants) {
    state.items = plants
  },
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  SET_ERROR(state, error) {
    state.error = error
  },
  ADD_PLANT(state, plant) {
    state.items.push(plant)
  },
  UPDATE_PLANT(state, updatedPlant) {
    const index = state.items.findIndex(p => p.id === updatedPlant.id)
    if (index !== -1) {
      state.items.splice(index, 1, updatedPlant)
    }
  },
  DELETE_PLANT(state, plantId) {
    state.items = state.items.filter(p => p.id !== plantId)
  }
}

const actions = {
  async fetchPlants({ commit }) {
    commit('SET_LOADING', true)
    try {
      const response = await axios.get('/api/plants')
      commit('SET_PLANTS', response.data)
      commit('SET_ERROR', null)
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  async createPlant({ commit }, plantData) {
    commit('SET_LOADING', true)
    try {
      const response = await axios.post('/api/plants', plantData)
      commit('ADD_PLANT', response.data)
      commit('SET_ERROR', null)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  async updatePlant({ commit }, { id, data }) {
    commit('SET_LOADING', true)
    try {
      const response = await axios.put(`/api/plants/${id}`, data)
      commit('UPDATE_PLANT', response.data)
      commit('SET_ERROR', null)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  async deletePlant({ commit }, id) {
    commit('SET_LOADING', true)
    try {
      await axios.delete(`/api/plants/${id}`)
      commit('DELETE_PLANT', id)
      commit('SET_ERROR', null)
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  async fetchPlantById({ commit }, id) {
    commit('SET_LOADING', true)
    try {
      const response = await axios.get(`/api/plants/${id}`)
      commit('SET_ERROR', null)
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  }
}

const getters = {
  getPlantById: state => id => {
    return state.items.find(plant => plant.id === id)
  },
  totalPlants: state => state.items.length,
  plantsByCategory: state => category => {
    return state.items.filter(plant => plant.category === category)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 